<?php

namespace App\Services;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Order;
use App\Models\ProductSku;
use App\Models\UserAddress;

class OrderService
{
    public function store(User $user, UserAddress $address, $remark, $items,$fromcart)
    {
        // 开启一个数据库事务
        $order = \DB::transaction(function () use ($user, $address, $remark, $items,$fromcart) {
            // 更新此地址的最后使用时间
            $address->update(['last_used_at' => Carbon::now()]);
            // 创建一个订单
            $order   = new Order([
                'address'      => [ // 将地址信息放入订单中
                    'address'       => $address->full_address,
                    'zip'           => $address->zip,
                    'contact_name'  => $address->contact_name,
                    'contact_phone' => $address->contact_phone,
                ],
                'remark'       => $remark,
                'payment_method' => '',
                'total_amount' => 0,
            ]);
            // 订单关联到当前用户
            $order->user()->associate($user);
            // 写入数据库
            $order->save();

            $totalAmount = 0;
            // 遍历用户提交的
            foreach ($items as $data) {
                $sku  = ProductSku::find($data['product_sku']['id']);
                // 创建一个 OrderItem 并直接与当前订单关联
                $item = $order->items()->make([
                    'amount' => $data['amount'],
                    'price'  => $data['product_sku']['price'],
                ]);
                $item->product()->associate($data['product_sku']['product']['id']);
                $item->productSku()->associate($sku);
                $item->save();
                $totalAmount += $data['product_sku']['price'] * $data['amount'];
                if ($data['product_sku']['stock']<= 0) {
                    return $res=['msg'=>'库存不足','code'=>'error'];
                    // throw new InvalidRequestException('该商品库存不足');
                }
            }
            // 更新订单总金额
            $order->update(['total_amount' => $totalAmount]);
            // 将下单的商品从购物车中移除
            if($fromcart){
                $cartIds = collect($items)->pluck('id')->all();
                app(CartService::class)->remove($cartIds);
            }
            return $order;
        });

        return $order;
    }
}